import { connect } from "mqtt";
import config from "../base.config";

class MQTT {
  constructor() {
    this.client = connect(config.mqtt.url, {
      username: config.mqtt.username,
      password: config.mqtt.password
    });

    this.listeners = {};

    this.client.on("message", (topic, payload) => {
      try {
        payload = JSON.parse(payload.toString());
      } catch (e) {
        console.log(e);
      }
      this.invokeEvent({ topic, payload });
    });
    this.client.on("connect", () => {
      console.log("mqtt connected !");
      this.client.subscribe(config.mqtt.topic, (err) => {
        console.log(`subscribe： ${config.mqtt.topic}`);
      });
    });
    this.client.on("disconnect", (msg) => {
      console.warn("disconnect", msg);
    });
  }
  addEventListener(topic, fn) {
    this.listeners[topic] = this.listeners[topic] || [];
    if (this.listeners[topic].indexOf(fn) === -1) {
      this.listeners[topic].push(fn);
    }

    return () => {
      this.listeners[topic] = this.listeners[topic].filter((callback) => {
        return callback !== fn;
      });
    };
  }
  invokeEvent({ topic, payload }) {
    let listeners = this.listeners[topic] || [];
    listeners.forEach((fn) => {
      fn.call(null, payload);
    });
  }
}

export default new MQTT();
